#!/usr/bin/env python3
import os
import re
import sys
import gzip
import subprocess

print("🍀 tge.rs - terminal game engine by rust...")
# example: ./gen_sdl_seqs assets/sdq/fire.gif assets/sdq/2.ssf 40 25
if len(sys.argv) != 5:
    print("🚀 USAGE: tools/gen_sdl_seqs <input_gif_file> <output_ssf_file> <width> <height>")
    sys.exit(0)

GIF = sys.argv[1]
SSF = sys.argv[2]
WIDTH = int(sys.argv[3])
HEIGHT = int(sys.argv[4])

print("🍀 extract pngs use ffmpeg...")
# 需要先安装ffmpeg: brew install ffmpeg
p = subprocess.Popen("ffmpeg -i " + GIF + " -vsync 0 tmp/t%d.png",
                     shell=True, 
                     stdout=subprocess.PIPE, 
                     stderr=subprocess.STDOUT)
stdout, stderr = p.communicate()

rf = re.compile(r"(.*)frame=(.*?)(\d+)(.*)")
fg = rf.match(str(stdout))
FRAME_COUNT=int(fg.group(3))
print("    frame_count = %d"%(FRAME_COUNT))

print("🍀 building tpetii...")
os.system("cargo build --bin tpetii --release")

print("🍀 tpetii convert png to sdl...")
for x in range(FRAME_COUNT):
    print("\r", x + 1, "  ", end='')
    cmd = "./target/release/tpetii tmp/t%d.png  %d %d > tmp/t%d.sdl" % (x + 1, WIDTH, HEIGHT, x + 1)
    os.system(cmd)

fsdq = open(SSF, "wb+") 

# tpetii生成的sdl文件，texture设置为255
# texture = 255 表示每个点拥有自己的texture
# 这种方式更灵活，但数据量会稍大
fsdq.write(b"width=%d,height=%d,texture=255,frame_count=%d\n"%(WIDTH, HEIGHT, FRAME_COUNT))

flens = []
rds = re.compile(r"(\d+),(\d+),(\d+)(.*?)")
datas = bytearray(b'')
for x in range(FRAME_COUNT):
    count = 0
    sdatas = bytearray(b'')
    for l in open("tmp/t%d.sdl"%(x+1), "r"):
        if count != 0:
            for ds in rds.findall(l[:-1]):
                sdatas.append(int(ds[0]))
                sdatas.append(int(ds[1]))
                sdatas.append(int(ds[2]))
        count += 1
    cs = gzip.compress(sdatas)
    flens.append(len(cs))
    datas += cs
for x in range(FRAME_COUNT):
    fsdq.write(bytes(("%d,"%(flens[x])).encode()))
fsdq.write(b"\n")
fsdq.write(datas)
fsdq.close()
print("\n🍀 %s write ok!"%SSF)


